import {Component, OnInit} from '@angular/core';
import {_HttpClient} from '@delon/theme';
import {ActivatedRoute, Router} from '@angular/router';
import {UtilityService} from '../../../../service/utils.service';
import {appConfig} from '../../../../service/common';
import {NzModalService, NzNotificationService} from 'ng-zorro-antd';
import {RoleModule} from '../../../../service/role/role.model';
import {PlatformLocation} from '@angular/common';


@Component({
  selector: 'app-operatorole',
  templateUrl: './operatorole.component.html',
})
export class OperatoroleComponent implements OnInit {

    constructor(
        private http: _HttpClient,
        private router: Router,
        private activatedRoute: ActivatedRoute, // 注入路由，接收到参数
        private modal: NzModalService,
        private nznot: NzNotificationService,
        private utilityService: UtilityService,
        location: PlatformLocation

    ) {
        // 浏览器点击后退事件
        location.onPopState(() => {
            this.router.navigateByUrl('/operator');
        });
    }

    role: RoleModule = new RoleModule(); // 绑定数据
    operatorGuid: string; // 操作guid
    operatoruserId: string; // 操作userId
    listloading = false;
    expandForm = false;
    loading = false;
    configTitle: any;
    total: number; // 总页数
    selectedRows: any; // 总数
    type = [
        { text: '正常', value: false, key: 'normal' },
        { text: '挂起', value: false, key: 'hang' },
        { text: '注销', value: false, key: 'logOut' },
        { text: '锁定', value: false, key: 'locking' }
    ];


    affiliation = [
        { text: 'APF应用', value: false, key: 'ABF' },
        { text: '测试应用', value: false,  key: 'TEST' },
    ]
    page: any; // 查询list变量
    modalVisible = false;
    pageIndex=1;
    list: any[] = []; // 角色列表
    data: any[] = []; // 表格数据
    headerData = [  // 配置表头内容
        {value: '角色名称' , key: 'roleName', isclick: false},
        {value: '角色代码', key: 'roleCode',  isclick: false},
        {value: '角色描述' , key: 'roleDesc', isclick: false},
    ];


    moreData = { morebutton: true,
        buttons: [
            {key: 'Overview' , value: '查看概况'},
            {key: 'Authority' , value: '权限配置'}
        ]
    }

    test: string;
    buttons = [
        {key: 'add', value: '分配角色',  buttonCode: appConfig.funcObject.operators.distributionRole}
    ]

    ngOnInit() {
        this.operatorGuid = this.activatedRoute.snapshot.params.id; // 拿到父组件传过来的操作员的guid来进行操作
        this.getUserid(this.operatorGuid); // 查询userId
        this.getData(); // 只会触发一次，但是ngchanges并不会触发咋办
        this.configTitle = {value: '修改', buttonCode: 'operNo'}
    }


    getData(option?) { // 初始化请求后台数据
        if (option) {
            this.pageIndex = 1;
        }

        this.page = {
            condition: this.objJson,
            page: {
                current: this.pageIndex,
                size: this.role.ps,
                orderByField: 'guid',
                guidOperator: this.operatorGuid,
                asc: false // asc 默认是true  升序排序，时间类型 用false， 降序
            }
        };
        this.listloading = true;
        this.utilityService.postData(appConfig.serverUrl  + appConfig.API.queryByOperator + '/' + this.operatorGuid , this.page)
            .subscribe(
                (val) => {
                    for (let i = 0; i <  val.result.records.length; i++) {
                        val.result.records[i].buttonData = [ {key: 'dels', value: '删除', if: false, buttonCode: appConfig.funcObject.operators.del}];
                    }
                    this.listloading = false;
                    this.data = val.result.records;
                    this.total = val.result.total;
                },
                error => {
                    this.listloading = false;
                    this.nznot.create('error', error.code , error.msg);
                }
            );
    }

    // 根据guid查询详情，获取userId
    getUserid(id) {
        this.utilityService.getData(appConfig.serverUrl + appConfig.API.acOperatorsAdd + '/' + id)
            .subscribe(
                (val) => {
                    this.operatoruserId = val.result.userId;
                }
            );
    }

    // 列表组件传过来的内容
    addHandler(event) {
        if (event === 'add') {
            console.log(this.operatoruserId)
            this.getroleList(this.operatoruserId); // 请求可添加的较色
            this.modalVisible = true;  // 此时点击了列表组件的新增，打开模态框
        } else{ // 代表修改，把修改的内容传递进去，重新渲染
            this.modalVisible = true;  // 此时点击了列表组件的新增，打开模态框
        }
    }

    // 查询

    // 列表传入的翻页数据
    monitorHandler(event) {
        this.pageIndex = event;
        this.getData();
    }

    // 接受子组件删除的数据 单条还是多条
    deleatData(event) {
        this.data = [
            {'id': 1, 'roleName': '汪波', 'roleCode': 'role001',  'guidApp': 'ABF', 'roleDesc': '角色一' },
            {'id': 2, 'roleName': '赵春海', 'roleCode': 'role002', 'guidApp': '柜面系统', 'roleDesc': '角色二' },
            {'id': 3, 'roleName': '王星名', 'roleCode': 'role003',  'guidApp': 'ABF', 'roleDesc': '角色三' },
            {'id': 4, 'roleName': '李毅', 'roleCode': 'role004',  'guidApp': '柜面系统', 'roleDesc': '角色四' }
        ];
    }


    // 列表按钮方法
    buttonDataHandler(event) {
        console.log(event); // 根据event.value来判断不同的请求，来获取结果和方法或者进行路由的跳转
        if (event.value ===  'Authority') {
            console.log(event.key);
        }

        if (event.value ===  'Overview') {
            console.log(event.key);
        }

    }


    // 删除按钮
    buttonEvent(event) {
        if(event.names.key === 'dels') {
            this.modal.open({
                title: '是否删除',
                content: '您确认要删除该角色吗',
                okText: '确定',
                cancelText: '取消',
                onOk: () => {
                    // 换接口即可
                    let deletaObj = {
                        operatorIdList: [this.operatorGuid],
                        roleIdList: [event.guid]
                    }
                    this.utilityService.postData(appConfig.serverUrl + appConfig.API.batchDelete, deletaObj )
                        .subscribe(
                            (val) => {
                                this.getData()
                                this.nznot.create('success', val.msg , val.msg);
                            },
                            (error) => {
                                this.nznot.create('error', error.msg , error.msg);
                            });

                },
                onCancel: () => {
                    console.log('失败');
                }
            });
        }
    }


    // 批量删除
    deleteBatch(event) {
        this.modal.open({
            title: '是否删除',
            content: '您是否确认删除这' + event.length + '个角色吗?',
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
                let delarray = [];
                for( let i = 0; i < event.length; i++) {
                    delarray.push(event[i].guid);
                }
                let deletaObj = {
                    operatorIdList: [this.operatorGuid],
                    roleIdList: delarray
                }
                this.utilityService.postData(appConfig.serverUrl + appConfig.API.batchDelete, deletaObj )
                    .subscribe(
                        (val) => {
                            this.getData();
                            this.selectedRows = []
                            this.nznot.create('success', val.msg , val.msg);
                        },
                        (error)=> {
                            this.nznot.create('error', error.msg , error.msg);
                        });
            },
            onCancel: () => {
                this.getData();
                this.selectedRows = []
            }
        });

    }


    selectedRow(event) { // 选中方法，折叠层按钮显示方法
        console.log(event);
    }



    // 处理行为代码，跳转、弹出框、其他交互
    isActive(event) {
        // 路由跳转
        this.router.navigate(['APPlication'],{ queryParams: { name: event } });
    }


    objJson = {};
    // 搜索框
    search() {
        this.objJson = this.role;
        this.getData(this.role);
    }

    // 重置搜索框
    reset() {
        this.role = new RoleModule();
        this.objJson = {};
        this.getData();
    }


    // 查询可分配的角色和已分配的角色
    getroleList(id){
        this.utilityService.getData(appConfig.serverUrl + appConfig.API.queryOperatorByRole + '/' + id)
            .subscribe(
                (val) => {
                    const ret = [];
                    for (let i = 0; i < val.result.length; i++) {
                        ret.push({
                            key: i.toString(),
                            title:val.result[i]['roleName'], // 名称
                            guid:val.result[i]['guid'], // guid
                            status: val.result[i]['exit'], // 状态，用来保存给后台的标识
                            description: val.result[i]['roleName'],  // 描述
                            direction: val.result[i]['exit'] === 'true' ? 'left' : 'right', // 在左边还是右边，协商的字段 exit，给true代表左边未分配的，false代表右边，已分配的
                        });
                    }
                    this.list = ret;
                },
                (error) => {
                    this.nznot.create('error', error.code,error.msg);
                });
    }


    //新增提交
    subAddrole(){
        let roleGuids = []
        console.log(this.list)
        for(let i = 0 ; i < this.list.length; i ++){
            if(this.list[i].status === 'right' || this.list[i].status === 'false'){
                roleGuids.push(this.list[i].guid);
            }
        }
        let jsonData = {
            list: roleGuids,
            operatorId: this.operatorGuid
        }
        this.utilityService.postData(appConfig.serverUrl  + appConfig.API.batchAddRole ,jsonData)
            .subscribe(
                (val) => {
                    this.modalVisible = false;
                    this.nznot.create('success', val.msg , val.msg);
                    this.getData();
                } ,
                (error) => {
                    this.nznot.create('error', error.code,error.msg);
                    this.modalVisible = false;

                }
            );
    }


    filterOption(inputValue, option) {
        return option.description.indexOf(inputValue) > -1;
    }



    searchpro(ret: any) {
        console.log('nzSearchChange', ret);
    }

    // 内容信息
    select(ret: any) {
        console.log('nzSelectChange', ret);
    }

    // 移动的时候 修改status这个状态标识，方便数据保存后台
    change(ret: any) {

        for(let i = 0; i < ret.list.length; i ++ ) {
            ret.list[i].status = ret.to;
        }
    }


}
